package mcia_administrative;

import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.*;

/**
 * DesktopRoomDesign.java - class used to upload room images and add Lights
 *
 * @author MCIA
 */
public class DesktopRoomDesign extends javax.swing.JFrame {

    private int lastNumberOfL = 0;                                              //initiating counter for units (Light)
    private int floorNumber = 1;                                                //which floor we are at
    private String currentCLname = DesktopFloorDesign.getCurrentCL();           //getting the name from prev screen
    private int xM, yM;                                                         //relative Mouse x and y coordinate
    private int x, y;                                                           //for improvement of button dragging
    private int positionSaved = 0;                                              //checks if the Mouse position is saved to make new CL
    private JLabel pointer1, pointer2, pointer3, pointer4;                      //pointers to see where we add CL
    private int widthL = 100;                                                    //default width of Light
    private int heightL = 30;                                                   //default height of Light
    private MouseMotionListener listener;                                       //listener for mouse dragged, etc.
    private MouseListener listener2;                                            //listener for mouse pressed, etc.
    public String currentUser = "Admin";                                        //name of current user (get from other window or set still)
    private ArrayList<Integer> freeLNumbers = new ArrayList<Integer>();         //list with Light parameters
    private String rememberImage = "";                                          //remembering inserted image

    /** Creates new form DesktopFloorDesign */
    public DesktopRoomDesign() {
        initComponents();

        //aligning imageLabel position within layeredPane
        int LP_w = layeredPane.getWidth();
        int LP_h = layeredPane.getHeight();
        imageLabel.setBounds(0, 0, LP_w, LP_h);

        //hiding descriptionLabel
        descriptionLabel.setText(DesktopFloorDesign.getCurrentCL());
        BigTitle.setText(DesktopFloorDesign.getCurrentCL() + " Design View");
        //setting text to status label
        statusLabel.setText("User: " + currentUser + " | Floor: " + floorNumber);

        //setting unvisible poiners
        pointer1 = new JLabel("+");
        pointer2 = new JLabel("+");
        pointer3 = new JLabel("+");
        pointer4 = new JLabel("+");
        layeredPane.add(pointer1);
        layeredPane.add(pointer2);
        layeredPane.add(pointer3);
        layeredPane.add(pointer4);
        pointer1.setName("map_image");
        pointer2.setName("map_image");
        pointer3.setName("map_image");
        pointer4.setName("map_image");
        pointer1.setVisible(false);
        pointer2.setVisible(false);
        pointer3.setVisible(false);
        pointer4.setVisible(false);
        pointer1.setForeground(Color.red);
        pointer2.setForeground(Color.red);
        pointer3.setForeground(Color.red);
        pointer4.setForeground(Color.red);

        listener = new MouseMotionListener() {

            public void mouseDragged(MouseEvent e) {
                try {
                    xM = layeredPane.getMousePosition().x - x;
                    yM = layeredPane.getMousePosition().y - y;
                    e.getComponent().setBounds(xM, yM, widthL, heightL);
                    repaint();
                } catch (NullPointerException ex) {
                    //we are out of the screen
                }
            }

            public void mouseMoved(MouseEvent e) {
                //nothing happens
            }
        };

        listener2 = new MouseListener() {

            public void mouseClicked(MouseEvent e) {
                //
            }

            public void mousePressed(MouseEvent e) {
                //get location where in the component were clicked
                x = e.getX();
                y = e.getY();
            }

            public void mouseReleased(MouseEvent e) {
                //saving new light position
                String name = e.getComponent().getName();
                int newX = e.getComponent().getX();
                int newY = e.getComponent().getY();

                //updating RemList
                for (int i = 0; i < Main.allLights.size(); i++) {
                    if (Main.allLights.get(i)[1].equals(name)) {
                        String[] newPositionL = Main.allLights.get(i);
                        newPositionL[2] = String.valueOf(newX);
                        newPositionL[3] = String.valueOf(newY);
                        Main.allLights.set(i, newPositionL);
                    }
                }
            }

            public void mouseEntered(MouseEvent e) {
                //
            }

            public void mouseExited(MouseEvent e) {
                //
            }
        };

        //loading existing units
        if (Main.allLights.size() > 0) {
            int sucess = loadUnits(currentCLname);
            if (sucess == -1) {
                System.out.println("Error: Loading existing units not sucessed!");
            }
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        fileChooser = new javax.swing.JFileChooser();
        jPanel2 = new javax.swing.JPanel();
        statusLabel = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        BigTitle = new javax.swing.JLabel();
        descriptionLabel = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        layeredPane = new javax.swing.JLayeredPane();
        imageLabel = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        deleteButton = new javax.swing.JButton();
        lightCombo = new javax.swing.JComboBox();
        addLightButton = new javax.swing.JButton();
        backButton = new javax.swing.JButton();
        addLSButton = new javax.swing.JButton();
        uploadRoomImageButton = new javax.swing.JButton();

        fileChooser.setDialogTitle("Choose Image For The Floor");
        fileChooser.setFileFilter(new MyCustomFilter());

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Test");
        setBounds(new java.awt.Rectangle(0, 0, 800, 600));
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jPanel2.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        statusLabel.setText("User: ? |  Floor: ?");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusLabel)
                .addContainerGap(681, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        jPanel3.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        BigTitle.setFont(new java.awt.Font("Tahoma", 0, 18));
        BigTitle.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        BigTitle.setText("CL Design View");

        descriptionLabel.setForeground(new java.awt.Color(51, 102, 255));
        descriptionLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        descriptionLabel.setText("Description Label");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(descriptionLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 774, Short.MAX_VALUE)
                    .addComponent(BigTitle, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 774, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addComponent(BigTitle, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(descriptionLabel)
                .addContainerGap())
        );

        jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

        layeredPane.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        layeredPane.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                layeredPaneMouseClicked(evt);
            }
        });

        imageLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        imageLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP);
        imageLabel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        imageLabel.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        imageLabel.setBounds(10, 10, 740, 370);
        layeredPane.add(imageLabel, javax.swing.JLayeredPane.DEFAULT_LAYER);
        imageLabel.getAccessibleContext().setAccessibleParent(jScrollPane1);

        jScrollPane1.setViewportView(layeredPane);

        jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "CL & Lights Edition", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION));

        deleteButton.setText("Delete");
        deleteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteButtonActionPerformed(evt);
            }
        });

        lightCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "- Select Unit -" }));
        lightCombo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                lightComboActionPerformed(evt);
            }
        });

        addLightButton.setText("Add Light");
        addLightButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addLightButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(addLightButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lightCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(deleteButton)
                .addGap(74, 74, 74))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(addLightButton, javax.swing.GroupLayout.DEFAULT_SIZE, 39, Short.MAX_VALUE)
                    .addComponent(lightCombo, javax.swing.GroupLayout.DEFAULT_SIZE, 39, Short.MAX_VALUE)
                    .addComponent(deleteButton, javax.swing.GroupLayout.DEFAULT_SIZE, 39, Short.MAX_VALUE))
                .addContainerGap())
        );

        backButton.setText("Back");
        backButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                backButtonActionPerformed(evt);
            }
        });

        addLSButton.setText("Edit Local Scenes");
        addLSButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addLSButtonActionPerformed(evt);
            }
        });

        uploadRoomImageButton.setText("Import Image ...");
        uploadRoomImageButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                uploadRoomImageButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addComponent(uploadRoomImageButton, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, 334, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(addLSButton, javax.swing.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(backButton, javax.swing.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(uploadRoomImageButton, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(7, 7, 7)
                        .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(backButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(addLSButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 48, Short.MAX_VALUE))))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(4, 4, 4)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 409, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Uploads room image
     *
     */
    private void uploadRoomImageButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_uploadRoomImageButtonActionPerformed
        int returnVal = fileChooser.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            try {
                //what to do with the file
                File sourceimage = new File(file.getAbsolutePath());
                Image image = ImageIO.read(sourceimage);
                ImageIcon icon = new ImageIcon(image);
                imageLabel.setIcon(icon);

                //setting image to bottom layer (to show up buttons)
                layeredPane.setLayer(imageLabel, 0);

                //resizing imageLabel and layeredPane to match picture size
                int imgW = image.getWidth(fileChooser);
                int imgH = image.getHeight(fileChooser);
                imageLabel.setBounds(0, 0, imgW, imgH);
                Dimension wymiary = new Dimension(imgW, imgH);
                layeredPane.setPreferredSize(wymiary);

                //saving image to RemList
                int i = 0;
                int maxLights = Main.allLights.size();
                int savedImg = 0;
                while (i < maxLights && savedImg == 0) {
                    if (Main.allLights.get(i)[0].equals(currentCLname)) {
                        System.out.println("Saved CL image.");
                        String[] line = Main.allLights.get(i);
                        line[4] = file.getAbsolutePath();
                        Main.allLights.set(i, line);
                        savedImg = 1;
                    }
                    i++;
                }
                if (savedImg == 0) {
                    rememberImage = file.getAbsolutePath();
                }

                System.out.println("Successfully loaded file.");
                descriptionLabel.setText("Image loaded. Add at least 1 light to save settings.");
            } catch (Exception ex) {
                descriptionLabel.setText("Problem accessing file!");
                System.out.println("Problem accessing file " + file.getAbsolutePath() + " Error: " + ex);
            }
        } else {
            System.out.println("File access cancelled by user.");
        }
    }//GEN-LAST:event_uploadRoomImageButtonActionPerformed
    /**
     * Used to mark position where mouse was clicked
     *
     */
    private void layeredPaneMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_layeredPaneMouseClicked
        //getting mouse coordinates relative to LayeredPane
        xM = layeredPane.getMousePosition().x;
        yM = layeredPane.getMousePosition().y;

        //showing pointer
        pointer1.setVisible(true);
        pointer1.setBounds(xM - (widthL / 2) + 23, yM - (heightL / 2) - 10, widthL, heightL);
        pointer2.setVisible(true);
        pointer2.setBounds(xM - (widthL / 2) + 23, yM + (heightL / 2) - 15, widthL, heightL);
        pointer3.setVisible(true);
        pointer3.setBounds(xM + (widthL / 2) - 28, yM - (heightL / 2) - 10, widthL, heightL);
        pointer4.setVisible(true);
        pointer4.setBounds(xM + (widthL / 2) - 28, yM + (heightL / 2) - 15, widthL, heightL);

        //showing info that mouse has been clicked
        descriptionLabel.setText("Position saved. Click 'Add Light' to add Light in this point.");
        positionSaved = 1;
    }//GEN-LAST:event_layeredPaneMouseClicked
    /**
     * Deleting particular Light
     *
     */
    private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
        //actions to delete particular CL or Light
        //we get text of CL or Light from comboList
        String whichToDelete = lightCombo.getSelectedItem().toString();
        int selected = lightCombo.getSelectedIndex();

        if (selected == 0) {
            descriptionLabel.setText("First select CL/Light from drop-down list!");
        }

        //we make sure that any CL or Light is selected
        if (selected != 0) {
            //we iterate over all components in layeredPane and look for one with the name that we want
            int toDel2 = 0;
            for (int i = 0; i < layeredPane.getComponentCount(); i++) {
                if (whichToDelete != null && whichToDelete.equals(layeredPane.getComponent(i).getName())) {
                    toDel2 = i;
                }
            }

            //adding number to list of free numbers
            String onlyNumber = whichToDelete;
            int lastDot = onlyNumber.lastIndexOf(".");
            onlyNumber = onlyNumber.substring(lastDot + 1);

            freeLNumbers.add(Integer.parseInt(onlyNumber));
            Collections.sort(freeLNumbers);

            //removing from list that is exported to text file
            for (int i = 0; i < Main.allLights.size(); i++) {
                if (Main.allLights.get(i)[1].equals(whichToDelete)) {
                    Main.allLights.remove(i);
                }
            }

            //removing from comboList
            lightCombo.setSelectedIndex(0);
            lightCombo.removeItemAt(selected);
            //removing from layeredPane
            layeredPane.remove(toDel2);
            layeredPane.repaint();
            descriptionLabel.setText(whichToDelete + " deleted");
        }
    }//GEN-LAST:event_deleteButtonActionPerformed
    /**
     * Not used yet
     *
     */
    private void lightComboActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_lightComboActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_lightComboActionPerformed
    /**
     * Add Light button
     *
     */
    private void addLightButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addLightButtonActionPerformed
        //showing info when position not clicked
        if (xM == 0 || yM == 0 || positionSaved == 0) {
            descriptionLabel.setText("Click on the image first.");
            return;
        }

        //setting mouse coordinates
        int newX = xM;
        int newY = yM;

        //computing middle of CL to insert button in the middle of mouse coordinates
        newX = newX - (widthL / 2);
        newY = newY - (heightL / 2);

        //making new button with CL name where the coordinates were pointed
        int newLnumber;
        if (freeLNumbers.isEmpty()) {
            lastNumberOfL++;
            newLnumber = lightCombo.getItemCount();
        } else {
            newLnumber = freeLNumbers.get(0);
            freeLNumbers.remove(0);

            for (int i = 0; i < freeLNumbers.size(); i++) {
                System.out.println("free no.: " + freeLNumbers.get(i));
            }
        }

        JButton newL = new JButton(DesktopFloorDesign.getFloorNum() + "." + DesktopFloorDesign.getCLnum() + "." + newLnumber);
        try {
            newL.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/bulb.jpg")));
        } catch (Exception ex) {
            System.out.println("No bulb icon in correct location: " + ex);
        }
        newL.setName("Light " + DesktopFloorDesign.getFloorNum() + "." + DesktopFloorDesign.getCLnum() + "." + newLnumber);
        newL.setBorderPainted(false);
        newL.setContentAreaFilled(false);
        newL.setDefaultCapable(false);
        newL.setHideActionText(true);
        newL.setBounds(newX, newY, widthL, heightL);
        newL.addMouseMotionListener(listener);
        newL.addMouseListener(listener2);
        layeredPane.add(newL);
        descriptionLabel.setText("");
        positionSaved = 0;

        //adding to RemList
        String[] lightCo;
        if (rememberImage.length() > 0) {
            lightCo = new String[]{currentCLname, newL.getName(), String.valueOf(newX), String.valueOf(newY), rememberImage};
            rememberImage = "";
        } else {
            lightCo = new String[]{currentCLname, newL.getName(), String.valueOf(newX), String.valueOf(newY), ""};
        }
        Main.allLights.add(lightCo); //adding light

        //setting image to bottom layer (to show up buttons)
        layeredPane.setLayer(imageLabel, 0);

        //hiding positioner (crosses around new CL)
        pointer1.setVisible(false);
        pointer2.setVisible(false);
        pointer3.setVisible(false);
        pointer4.setVisible(false);

        //adding Light to comboList in good position (sort)
        int howMany = lightCombo.getItemCount();
        String light = "Light ";
        String newLight = light + newL.getText();

        boolean added = false;
        for (int i = 0; i < howMany; i++) {
            Object obj = lightCombo.getItemAt(i);
            int compare = newLight.compareToIgnoreCase(obj.toString());
            if (compare <= 0 && (newLight.length() == obj.toString().length())) {
                lightCombo.insertItemAt(newLight, i);
                added = true;
                break;
            }
        }
        if (!added) {
            lightCombo.addItem(newLight);
        }

        //setting description
        descriptionLabel.setText(DesktopFloorDesign.getCurrentCL());
    }//GEN-LAST:event_addLightButtonActionPerformed

    private void backButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backButtonActionPerformed
        //going back to prev Screen
        DesktopFloorDesign prevScr = new DesktopFloorDesign();
        Main.changeFrame(prevScr);
    }//GEN-LAST:event_backButtonActionPerformed

    public static int getFloor() {
        return DesktopFloorDesign.getFloorNum();
    }

    private int loadUnits(String currentCLname) {
        //loading currentFloor
        if (Main.allLights.size() > 0) {
            //clearing layeredPane
            clearLayeredPane(layeredPane);

            //loading existing components from Main.allUnits variable
            lightCombo.removeAllItems();
            lightCombo.addItem("- Select Unit -");
            int howManyLights = 0;
            for (int i = 0; i < Main.allLights.size(); i++) {
                if (Main.allLights.get(i)[0].equals(currentCLname)) {

                    //adding Light to comboList in sorted order
                    int howMany = lightCombo.getItemCount();
                    String newLight = Main.allLights.get(i)[1];

                    boolean added = false;
                    for (int j = 0; j < howMany; j++) {
                        Object obj = lightCombo.getItemAt(j);
                        int compare = newLight.compareToIgnoreCase(obj.toString());
                        if (compare <= 0) {
                            lightCombo.insertItemAt(newLight, j);
                            added = true;
                            break;
                        }
                    }
                    if (!added) {
                        lightCombo.addItem(newLight);
                    }

                    howManyLights++;
                }
            }
            this.lastNumberOfL = howManyLights;

            //loading floor Lights
            for (int j = 0; j < Main.allLights.size(); j++) {
                if (Main.allLights.get(j)[0].equals(currentCLname)) {
                    int newX = Integer.parseInt(Main.allLights.get(j)[2]);
                    int newY = Integer.parseInt(Main.allLights.get(j)[3]);

                    String lightNo = Main.allLights.get(j)[1].substring(6, Main.allLights.get(j)[1].length());
                    JButton newL = new JButton(lightNo);
                    try {
                        newL.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/bulb.jpg")));
                    } catch (Exception ex) {
                        System.out.println("No bulb icon in correct location: " + ex);
                    }
                    newL.setName(Main.allLights.get(j)[1]);
                    newL.setBorderPainted(false);
                    newL.setContentAreaFilled(false);
                    newL.setDefaultCapable(false);
                    newL.setHideActionText(true);
                    newL.setBounds(newX, newY, widthL, heightL);
                    newL.addMouseMotionListener(listener);
                    newL.addMouseListener(listener2);
                    layeredPane.add(newL);
                }
            }

            //loading image
            for (int i = 0; i < Main.allLights.size(); i++) {
                if (Main.allLights.get(i)[0].equals(currentCLname) && !Main.allLights.get(i)[4].equals("")) {
                    String path = Main.allLights.get(i)[4];
                    try {
                        File sourceimage = new File(path);
                        Image image = ImageIO.read(sourceimage);
                        ImageIcon icon = new ImageIcon(image);
                        imageLabel.setIcon(icon);

                        //resizing imageLabel and layeredPane to match picture size
                        int imgW = icon.getIconWidth();
                        int imgH = icon.getIconHeight();
                        imageLabel.setBounds(0, 0, imgW, imgH);
                        Dimension dims = new Dimension(imgW, imgH);
                        layeredPane.setPreferredSize(dims);
                    } catch (IOException ex) {
                        Logger.getLogger(DesktopFloorDesign.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    break;
                }
            }

            //setting image to bottom layer (to show up buttons)
            layeredPane.setLayer(imageLabel, 0);

            /*saving missing numbers to freeLightsNumbers list*/
            //finding higher light number
            int lastIndex = 0;
            int actualHighest = 0;
            for (int i = 0; i < Main.allLights.size(); i++) {
                if (Main.allLights.get(i)[0].equals(currentCLname)) {
                    int higherNoDot = Main.allLights.get(i)[1].lastIndexOf(".");
                    int higherNo = Integer.parseInt(Main.allLights.get(i)[1].substring(higherNoDot + 1));
                    if (higherNo > actualHighest) {
                        actualHighest = higherNo;
                        lastIndex = i;
                    }
                }
            }

            int higherNoDot = Main.allLights.get(lastIndex)[1].lastIndexOf(".");
            int higherNo = Integer.parseInt(Main.allLights.get(lastIndex)[1].substring(higherNoDot + 1));

            //looking for missing numbers
            int found = 0;
            for (int howManyNumbers = 1; howManyNumbers < higherNo; howManyNumbers++) {
                found = 0;
                for (int i = 0; i < Main.allLights.size(); i++) {
                    if (Main.allLights.get(i)[0].equals(currentCLname)) {
                        String lookFor = "Light " + currentCLname.substring(3) + "." + howManyNumbers;
                        if (Main.allLights.get(i)[1].equals(lookFor)) {
                            found = 1;
                            break;
                        }
                    }
                    if (i == (Main.allLights.size() - 1) && found == 0) {
                        freeLNumbers.add(howManyNumbers);
                    }
                }
            }
            Collections.sort(freeLNumbers);
            /*-------------------------------------------------------------------*/
        } else {
            return -1;
        }

        return 0;
    }

    public void clearLayeredPane(JLayeredPane pane) {
        imageLabel.setName("map_image");
        //deleting all components in layeredPane except of image map
        int howMany = pane.getComponentCount();
        int j = 0;
        while (j < howMany) {
            int i = j;
            int howMany2 = pane.getComponentCount();
            while (i < howMany2) {
                if (pane.getComponent(i).getName() == null || !pane.getComponent(i).getName().equals("map_image")) {
                    pane.remove(i);
                    howMany2 = pane.getComponentCount();
                } else {
                    i++;
                }
            }
            j++;
        }
        pane.repaint();
    }

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        //
    }//GEN-LAST:event_formWindowClosing

    private void addLSButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addLSButtonActionPerformed
        //changing screen
        ScenesForCL scenescl = new ScenesForCL();
        scenescl.setVisible(true);
    }//GEN-LAST:event_addLSButtonActionPerformed
    /**
     * Setting Windows Look and Feel
     *
     */
    public static void main(String args[]) {
        //setting Windows Look and Feel
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception ex) {
            System.out.println("Error setting native LAF: " + ex);
        }

        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                DesktopFloorDesign thisFrame = new DesktopFloorDesign();
                String[] vars = null;
                Main.main(vars);
                Main.changeFrame(thisFrame);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel BigTitle;
    private javax.swing.JButton addLSButton;
    private javax.swing.JButton addLightButton;
    private javax.swing.JButton backButton;
    private javax.swing.JButton deleteButton;
    private javax.swing.JLabel descriptionLabel;
    private javax.swing.JFileChooser fileChooser;
    private javax.swing.JLabel imageLabel;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLayeredPane layeredPane;
    private javax.swing.JComboBox lightCombo;
    private javax.swing.JLabel statusLabel;
    private javax.swing.JButton uploadRoomImageButton;
    // End of variables declaration//GEN-END:variables
}
